package embed

import (
	_ "embed"
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/go-viper/model"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
)

//go:embed config.yaml
var f []byte

func ReaddEmbed() {
	os.Setenv("server.port", "8081")

	//embed 方式 ,作为默认配置项
	config := viper.New()
	//开始读取环境变量，如果没有调用这个函数，则下面无法读取到path的值
	config.AutomaticEnv()
	config.SetConfigType("yaml")
	//config.ReadConfig(bytes.NewReader(f))

	file, err := os.Open("E:\\develop\\gin-practice\\go-viper\\config.yaml")
	if nil != err {
		panic(fmt.Errorf("Fatal error config file2: %s \n", err))
	}
	config.ReadConfig(file)

	fmt.Println("Server Port:", config.GetInt("server.port"))
	fmt.Println("Database User:", config.GetString("database.user"))

	config.WatchConfig()

	// 配置读到结构体
	var cfg model.Configuration
	if err := config.Unmarshal(&cfg); err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(cfg)
	}

	// 监听配置变化
	config.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("embed file changed:", e.Name)
		if err := config.Unmarshal(&cfg); err != nil {
			fmt.Println(err)
		}
	})
	if err := config.Unmarshal(&cfg); err != nil {
		fmt.Println(err)
	}
}
